import { HttpException, HttpStatus } from '@nestjs/common';
import { Middleware, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import * as jwt from 'jsonwebtoken';
import { SECRET } from '../config';
import { UserService } from './user.service';

@Middleware()
export class AuthMiddleware implements NestMiddleware {
  constructor(private readonly userService: UserService) {}
  resolve(): (req: Request, res: Response, next: NextFunction) => void {
    return async (req: Request, res: Response, next: NextFunction) => {
      // 判断请求头是否包含authorization 如果存在 判断是否有token
      if (
        req.headers.authorization &&
        (req.headers.authorization as string).split(' ')[0] === 'token'
      ) {
        const token = (req.headers.authorization as string).split(' ')[1];
        const decoded: any = jwt.verify(token, SECRET);
        // 验证token
        const user = await this.userService.findById(decoded.id);
        if (!user) {
          throw new HttpException('User not found', HttpStatus.UNAUTHORIZED);
        }
        next();
      } else {
        throw new HttpException('Not authorized', HttpStatus.UNAUTHORIZED);
      }
    };
  }
}
